/**
 * 校园二手交易平台 - 分类API服务
 * 提供商品分类管理、分类浏览、分类推荐等功能
 */

import BaseService, { ApiResponse, PaginatedResponse } from './baseService';
import {
  Category,
  CategoryTreeNode,
  CategoryQueryParams,
  CategoryStats,
  CategoryRecommendation,
  DEFAULT_CATEGORY_QUERY_PARAMS,
} from '../types/category';
import { Product } from '../types/product';
import { mockCategories, mockCategoryTree, mockCategoryStats } from '../mock/category';

/**
 * 分类服务类
 */
export class CategoryService extends BaseService {
  private useMock: boolean = process.env.NODE_ENV === 'development';
  
  constructor(baseURL?: string) {
    super(baseURL || '/api/categories');
  }

  /**
   * 获取分类列表
   */
  async getCategories(params: CategoryQueryParams = {}): Promise<Category[]> {
    const queryParams = { ...DEFAULT_CATEGORY_QUERY_PARAMS, ...params };
    
    if (this.useMock) {
      return this.getMockCategories(queryParams);
    }
    
    return this.get<Category[]>('/list', queryParams);
  }

  /**
   * 获取分类详情
   */
  async getCategory(id: string): Promise<Category> {
    if (this.useMock) {
      return this.getMockCategory(id);
    }
    
    return this.get<Category>(`/${id}`);
  }

  /**
   * 获取分类树
   */
  async getCategoryTree(): Promise<CategoryTreeNode[]> {
    if (this.useMock) {
      return this.getMockCategoryTree();
    }
    
    return this.get<CategoryTreeNode[]>('/tree');
  }

  /**
   * 获取分类统计信息
   */
  async getCategoryStats(): Promise<CategoryStats[]> {
    if (this.useMock) {
      return this.getMockCategoryStats();
    }
    
    return this.get<CategoryStats[]>('/stats');
  }

  /**
   * 获取分类下的商品
   */
  async getCategoryProducts(categoryId: string, params?: any): Promise<Product[]> {
    if (this.useMock) {
      return this.getMockCategoryProducts(categoryId, params);
    }
    
    return this.get<Product[]>(`/${categoryId}/products`, params);
  }

  /**
   * 获取分类推荐
   */
  async getCategoryRecommendations(userId?: string): Promise<CategoryRecommendation[]> {
    if (this.useMock) {
      return this.getMockCategoryRecommendations(userId);
    }
    
    return this.get<CategoryRecommendation[]>('/recommendations', { userId });
  }

  /**
   * 搜索分类
   */
  async searchCategories(query: string): Promise<Category[]> {
    if (this.useMock) {
      return this.searchMockCategories(query);
    }
    
    return this.get<Category[]>('/search', { query });
  }

  /**
   * 获取热门分类
   */
  async getHotCategories(limit: number = 10): Promise<Category[]> {
    if (this.useMock) {
      return this.getMockHotCategories(limit);
    }
    
    return this.get<Category[]>('/hot', { limit });
  }

  // ==================== Mock 数据实现 ====================

  private async getMockCategories(params: CategoryQueryParams): Promise<Category[]> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    let categories = [...mockCategories];
    
    // 状态筛选
    if (params.status) {
      categories = categories.filter(category => category.status === params.status);
    }
    
    // 层级筛选
    if (params.level !== undefined) {
      categories = categories.filter(category => category.level === params.level);
    }
    
    // 父级分类筛选
    if (params.parentId) {
      categories = categories.filter(category => category.parentId === params.parentId);
    }
    
    return categories;
  }

  private async getMockCategory(id: string): Promise<Category> {
    await new Promise(resolve => setTimeout(resolve, 150));
    
    const category = mockCategories.find(cat => cat.id === id);
    if (!category) {
      throw new Error(`分类不存在: ${id}`);
    }
    
    return category;
  }

  private async getMockCategoryTree(): Promise<CategoryTreeNode[]> {
    await new Promise(resolve => setTimeout(resolve, 300));
    return mockCategoryTree;
  }

  private async getMockCategoryStats(): Promise<CategoryStats[]> {
    await new Promise(resolve => setTimeout(resolve, 250));
    return mockCategoryStats;
  }

  private async getMockCategoryProducts(categoryId: string, params?: any): Promise<Product[]> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    // 这里应该从商品Mock数据中筛选，暂时返回空数组
    // 在实际开发中，这里会调用商品服务获取数据
    return [];
  }

  private async getMockCategoryRecommendations(userId?: string): Promise<CategoryRecommendation[]> {
    await new Promise(resolve => setTimeout(resolve, 300));
    
    const recommendations: CategoryRecommendation[] = [
      {
        categoryId: 'electronics',
        categoryName: '电子产品',
        reason: '根据您的浏览历史推荐',
        score: 0.85,
        products: []
      },
      {
        categoryId: 'books',
        categoryName: '教材资料',
        reason: '与您专业相关',
        score: 0.78,
        products: []
      },
      {
        categoryId: 'clothing',
        categoryName: '服装服饰',
        reason: '热门分类',
        score: 0.65,
        products: []
      }
    ];
    
    return recommendations;
  }

  private async searchMockCategories(query: string): Promise<Category[]> {
    await new Promise(resolve => setTimeout(resolve, 200));
    
    const normalizedQuery = query.toLowerCase();
    return mockCategories.filter(category => 
      category.name.toLowerCase().includes(normalizedQuery) ||
      category.description?.toLowerCase().includes(normalizedQuery)
    );
  }

  private async getMockHotCategories(limit: number): Promise<Category[]> {
    await new Promise(resolve => setTimeout(resolve, 150));
    
    // 根据商品数量排序的热门分类
    const sortedCategories = [...mockCategories].sort((a, b) => 
      (b.productCount || 0) - (a.productCount || 0)
    );
    
    return sortedCategories.slice(0, limit);
  }
}

// 创建分类服务实例
export const categoryService = new CategoryService();

export default categoryService;